<template>
  <div class="app-container">
    <!-- 基础信息卡片 -->
    <el-card class="base-info-card" shadow="never">
      <div slot="header" class="base-info-title">
        <span>基础信息</span>
      </div>
      <el-form :model="form" :rules="rules" ref="formRef" label-width="140px" size="small" class="base-info-form">
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="采购订单编号" prop="po_code" required label-width="140px">
              <div class="input-switch-group">
                <el-input v-model="form.po_code" placeholder="请输入或自动生成" :readonly="form.auto_code || !!form.po_id" />
                <el-switch v-model="form.auto_code" style="margin-left: 8px;" @change="handleAutoCodeChange" :disabled="!!form.po_id" />
                <span class="switch-label">自动生成</span>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="批次编号" prop="batch_code" required label-width="140px">
              <div class="input-switch-group">
                <el-input v-model="form.batch_code" placeholder="请输入或自动生成" :readonly="form.auto_batch_code || !!form.po_id" />
                <el-switch v-model="form.auto_batch_code" style="margin-left: 8px;" @change="handleAutoBatchCodeChange" :disabled="!!form.po_id" />
                <span class="switch-label">自动生成</span>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="付款条款" prop="payment_terms" label-width="140px">
               <el-select v-model="form.payment_terms" placeholder="请选择付款条款">
                 <el-option label="30天账期" value="30天账期" />
                 <el-option label="60天账期" value="60天账期" />
                 <el-option label="现款现货" value="现款现货" />
                 <el-option label="货到付款" value="货到付款" />
                 <el-option label="货到10天内付款" value="货到10天内付款" />
               </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="供应商" prop="supplier_name" required label-width="140px">
              <el-input v-model="form.supplier_name" placeholder="请选择供应商" readonly>
                <template slot="append">
                  <el-button icon="el-icon-search" @click="supplierDialogVisible = true" />
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="采购订单名称" prop="po_name" label-width="140px">
               <el-input v-model="form.po_name" placeholder="请输入采购订单名称" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="期望交货日期" prop="expected_delivery_date" required label-width="140px">
               <el-date-picker v-model="form.expected_delivery_date" type="date" placeholder="请选择期望交货日期" style="width: 205px;" :picker-options="datePickerOptions" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="货币" prop="currency" required label-width="140px">
               <el-select v-model="form.currency" placeholder="请选择货币">
                 <el-option label="CNY" value="CNY" />
                 <el-option label="USD" value="USD" />
                 <el-option label="EUR" value="EUR" />
               </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="采购类型" prop="purchase_type" required label-width="140px">
               <el-select v-model="form.purchase_type" placeholder="请选择" @change="handlePurchaseTypeChange">
                 <el-option label="生产采购" value="生产采购" />
                 <el-option label="物料采购" value="物料采购" />
                 <el-option label="产品采购" value="产品采购" />
               </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <!-- 可扩展其他字段 -->
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark" label-width="140px">
              <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 下半部分：采购商品选择表格 -->
    <div class="goods-section">
      <div style="margin-bottom: 10px; display: flex; justify-content: space-between; align-items: center;">
        <span style="font-weight: bold;">采购商品</span>
        <div>
          <el-button type="primary" size="mini" @click="handleAddGoods">添加商品</el-button>
          <el-button size="mini" icon="el-icon-refresh" @click="handleResetGoodsList">重置列表</el-button>
        </div>
      </div>
      <el-table :data="goodsListPaginated" style="width: 100%" border>
        <el-table-column prop="goods_code" label="商品编号" align="center" />
        <el-table-column prop="goods_name" label="商品名称" align="center" />
        <el-table-column prop="stock_sfn" label="规格型号" align="center" />
        <el-table-column prop="unit_name" label="单位" align="center" width="80" />
        <el-table-column prop="quantity_num" label="采购数量" align="center" width="180">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.quantity_num" :min="1" size="mini" />
          </template>
        </el-table-column>
        <el-table-column prop="unit_price" label="单价" align="center" width="120">
          <template slot-scope="scope">
            {{ (scope.row.unit_price || 0).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="total_price" label="总价" align="center" width="120">
          <template slot-scope="scope">
            ¥{{ calcTotalPrice(scope.row) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="80">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="removeGoods(scope.$index + (goodsPageQuery.pageNum - 1) * goodsPageQuery.pageSize)">移除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin: 16px 0; text-align: right;">
        <pagination
          v-show="goodsList.length > 0"
          :total="goodsList.length"
          :page.sync="goodsPageQuery.pageNum"
          :limit.sync="goodsPageQuery.pageSize"
          @pagination="handleGoodsPageChange"
        />
      </div>
    </div>

    <!-- 底部操作按钮 -->
    <div style="margin-top: 30px; text-align: center;">
      <el-button type="primary" @click="handleSubmit">保存</el-button>
      <el-button type="success" @click="handleSubmitAndSubmit">保存并提交</el-button>
      <el-button @click="handleCancel">取消</el-button>
    </div>

    <!-- 商品选择弹窗（可后续实现） -->
    <!-- <el-dialog title="选择商品" :visible.sync="goodsDialogVisible" width="800px">
      <el-table
        :data="goodsSelectList"
        style="width: 100%"
        border
        ref="goodsSelectTable"
        @selection-change="handleGoodsSelectChange"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column prop="goods_code" label="商品编号" align="center" />
        <el-table-column prop="goods_name" label="商品名称" align="center" />
        <el-table-column prop="stock_sfn" label="规格型号" align="center" />
        <el-table-column prop="unit_name" label="单位" align="center" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="goodsDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="addSelectedGoods">添加</el-button>
      </span>
    </el-dialog> -->
    <!-- 物料商品弹窗 -->
    <el-dialog title="物料商品列表" :visible.sync="goodsDialogMaterialVisible" width="1000px">
      <div style="margin-bottom: 10px; display: flex; gap: 10px;">
        <el-input v-model="goodsMaterialQuery.material_code" placeholder="请输入商品编号" size="small" style="width: 180px;" />
        <el-button type="primary" size="small" @click="handleMaterialSearch">搜索</el-button>
        <el-button size="small" @click="handleMaterialReset">重置</el-button>
      </div>
      <el-table :data="goodsMaterialList" style="width: 100%" border ref="goodsMaterialTable" @selection-change="handleGoodsSelectChange">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column prop="material_code" label="商品编号" align="center" show-overflow-tooltip />
        <el-table-column prop="material_name" label="商品名称" align="center" show-overflow-tooltip />
        <el-table-column prop="material_sfn" label="规格型号" align="center" show-overflow-tooltip />
        <el-table-column prop="material_unit" label="单位" align="center" />
        <el-table-column prop="material_purchasePrice" label="采购价格" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ scope.row.material_purchasePrice || '0.00' }}
          </template>
        </el-table-column>
      </el-table>
      <div style="margin: 16px 0; text-align: right;">
        <pagination
          v-show="goodsMaterialQuery.total>0"
          :total="goodsMaterialQuery.total"
          :page.sync="goodsMaterialQuery.params.pageNum"
          :limit.sync="goodsMaterialQuery.params.pageSize"
          @pagination="fetchMaterialGoods"
        />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="goodsDialogMaterialVisible = false">关闭</el-button>
        <el-button type="primary" @click="addSelectedGoodsMaterial">添加</el-button>
      </span>
    </el-dialog>
    <!-- 产品商品弹窗 -->
    <el-dialog title="产品商品列表" :visible.sync="goodsDialogProductVisible" width="1000px">
      <div style="margin-bottom: 10px; display: flex; gap: 10px;">
        <el-input v-model="goodsProductQuery.product_code" placeholder="请输入商品编号" size="small" style="width: 180px;" />
        <el-button type="primary" size="small" @click="handleProductSearch">搜索</el-button>
        <el-button size="small" @click="handleProductReset">重置</el-button>
      </div>
      <el-table :data="goodsProductList" style="width: 100%" border ref="goodsProductTable" @selection-change="handleGoodsSelectChange">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column prop="product_code" label="商品编号" align="center" show-overflow-tooltip />
        <el-table-column prop="product_name" label="商品名称" align="center" show-overflow-tooltip />
        <el-table-column prop="product_sfn" label="规格型号" align="center" show-overflow-tooltip />
        <el-table-column prop="product_unit" label="单位" align="center" />
        <el-table-column prop="material_purchasePrice" label="采购价格" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ scope.row.material_purchasePrice || '0.00' }}
          </template>
        </el-table-column>
      </el-table>
      <div style="margin: 16px 0; text-align: right;">
        <pagination
          v-show="goodsProductQuery.total>0"
          :total="goodsProductQuery.total"
          :page.sync="goodsProductQuery.params.pageNum"
          :limit.sync="goodsProductQuery.params.pageSize"
          @pagination="fetchProductGoods"
        />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="goodsDialogProductVisible = false">关闭</el-button>
        <el-button type="primary" @click="addSelectedGoodsProduct">添加</el-button>
      </span>
    </el-dialog>
    <!-- 生产商品弹窗 -->
    <el-dialog title="生产商品列表" :visible.sync="goodsDialogProduceVisible" width="1000px">
      <div style="margin-bottom: 10px; display: flex; gap: 10px;">
        <el-input v-model="goodsProduceQuery.product_code" placeholder="请输入商品编号" size="small" style="width: 180px;" />
        <el-button type="primary" size="small" @click="handleProduceSearch">搜索</el-button>
        <el-button size="small" @click="handleProduceReset">重置</el-button>
      </div>
      <el-table :data="goodsProduceList" style="width: 100%" border ref="goodsProduceTable" @selection-change="handleGoodsSelectChange">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column prop="product_code" label="商品编号" align="center" show-overflow-tooltip />
        <el-table-column prop="product_name" label="商品名称" align="center" show-overflow-tooltip />
        <el-table-column prop="material_sfn" label="规格型号" align="center" show-overflow-tooltip />
        <el-table-column prop="material_unit" label="单位" align="center" />
        <el-table-column prop="required_quantity" label="需求数量" align="center" width="100">
          <template slot-scope="scope">
            {{ scope.row.required_quantity || '0' }}
          </template>
        </el-table-column>
        <el-table-column prop="material_purchasePrice" label="采购价格" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ scope.row.material_purchasePrice || '0.00' }}
          </template>
        </el-table-column>
      </el-table>
      <div style="margin: 16px 0; text-align: right;">
        <pagination
          v-show="goodsProduceQuery.total>0"
          :total="goodsProduceQuery.total"
          :page.sync="goodsProduceQuery.pageNum"
          :limit.sync="goodsProduceQuery.pageSize"
          @pagination="fetchProduceGoods"
        />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="goodsDialogProduceVisible = false">关闭</el-button>
        <el-button type="primary" @click="addSelectedGoodsProduce">添加</el-button>
      </span>
    </el-dialog>

    <!-- 供应商选择弹窗 -->
    <el-dialog title="供应商选择" :visible.sync="supplierDialogVisible" width="900px">
      <div style="margin-bottom: 10px; display: flex; gap: 10px;">
        <el-input v-model="supplierQuery.name" placeholder="请输入供应商名称" size="small" style="width: 180px;" />
        <el-button type="primary" size="small" @click="handleSupplierSearch">搜索</el-button>
        <el-button size="small" @click="handleSupplierReset">重置</el-button>
      </div>
      <el-table :data="supplierSelectList" style="width: 100%" border @row-click="selectSupplierAndClose" highlight-current-row>
        <el-table-column prop="supplier_name" label="供应商名称" align="center" />
        <el-table-column prop="supplier_person" label="联系人" align="center" />
        <el-table-column prop="supplier_phone" label="联系电话" align="center" />
      </el-table>
      <div style="margin: 16px 0; text-align: right;">
        <pagination
          v-show="supplierQuery.total>0"
          :total="supplierQuery.total"
          :page.sync="supplierQuery.params.pageNum"
          :limit.sync="supplierQuery.params.pageSize"
          @pagination="fetchSuppliers"
        />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="supplierDialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
/**
 * @description 采购订单新增组件
 * 用于创建新的采购订单，包括订单基本信息和商品选择
 */
import { listMaterialGoods, selectOrderLine_id, listProductGoods, listPurchaseGoods, listSupplier, addPurchaseOrder } from "@/views/ck/js/purchase"
import Pagination from "@/components/Pagination"
import { getAutoNumbers, getAutoNumbersConsume } from "@/api/basic/numbers";


export default {
  name: 'AddPurchaseOrder',
  components: {
    Pagination
  },
  data() {
    const validateDeliveryDate = (rule, value, callback) => {
      const today = new Date();
      today.setHours(0, 0, 0, 0);
      if (value && new Date(value) <= today) {
        callback(new Error('期望交货日期必须大于今天'));
      } else {
        callback();
      }
    };
    return {
      datePickerOptions: {
        disabledDate(time) {
          // 禁用今天及之前的日期
          return time.getTime() <= Date.now();
        }
      },
      // 采购订单表单数据
      form: {
        po_id: '',            // 采购订单ID
        po_code: '',          // 采购订单编号
        auto_code: false,     // 是否自动生成编号
        batch_code: '',       // 批次编号
        auto_batch_code: false, // 是否自动生成批次编号
        po_name: '',          // 采购订单名称
        supplier_id: '',      // 供应商ID
        supplier_name: '',    // 供应商名称
        expected_delivery_date: '', // 期望交货日期
        currency: 'CNY',      // 货币类型，默认人民币
        payment_terms: '',    // 付款条款
        purchase_type: '生产采购', // 采购类型，默认生产采购
        status: '1', // 订单状态，1-待提交
        remark: '',            // 备注
        create_by: '',         // 创建人
        update_by: ''          // 更新人
      },
      // 表单验证规则
      rules: {
        po_code: [
          { required: true, message: '请输入或生成采购订单编号', trigger: ['blur', 'change'] }
        ],
        batch_code: [
          { required: true, message: '请输入或生成批次编号', trigger: ['blur', 'change'] }
        ],
        po_name: [{ required: true, message: '请输入采购订单名称', trigger: ['blur', 'change'] }],
        supplier_id: [{ required: true, message: '请选择供应商', trigger: 'change' }],
        supplier_name: [{ required: true, message: '请输入供应商名称', trigger: 'blur' }],
        expected_delivery_date: [
          { required: true, message: '请选择期望交货日期', trigger: ['change', 'blur'] },
          { validator: validateDeliveryDate, trigger: ['change', 'blur'] }
        ],
        currency: [{ required: true, message: '请选择货币', trigger: 'change' }],
        payment_terms: [{ required: true, message: '请选择付款条款', trigger: 'change' }],
        purchase_type: [{ required: true, message: '请选择采购类型', trigger: 'change' }],
        remark: [{ required: false }]
      },
      goodsList: [],               // 采购订单中已选择的商品列表
      originalGoodsList: [],         // 原始商品列表，用于修改时的重置
      goodsDialogVisible: false,   // 通用商品选择弹窗显示状态
      goodsDialogMaterialVisible: false, // 物料商品弹窗显示状态
      goodsDialogProductVisible: false,  // 产品商品弹窗显示状态
      goodsDialogProduceVisible: false,  // 生产商品弹窗显示状态
      goodsMaterialList: [],       // 物料类商品数据列表
      goodsProductList: [],        // 产品类商品数据列表
      goodsProduceList: [],        // 生产类商品数据列表
      goodsSelected: [],           // 当前选中的商品数组
      supplierDialogVisible: false, // 供应商选择弹窗显示状态
      supplierSelectList: [],      // 供应商数据列表
      supplierQuery: {             // 供应商查询参数
        supplier_name: '',             // 供应商名称查询条件
        params :{
          pageNum: 1,                // 当前页码
          pageSize: 10          // 每页条数
        },
        total: 0                   // 总记录数
      }, 
      goodsMaterialQuery: {        // 物料商品查询参数
        material_code: '',           // 物料编码查询条件
        params :{
          pageNum: 1,                // 当前页码
          pageSize: 10          // 每页条数
        },
        total: 0                   // 总记录数
      }, 
      goodsProductQuery: {         // 产品商品查询参数
        product_code: '',                  // 产品编码查询条件
        params :{
          pageNum: 1,                // 当前页码
          pageSize: 10          // 每页条数
        },
        total: 0                   // 总记录数
      }, 
      goodsProduceQuery: {         // 生产商品查询参数
        product_code: '',                  // 生产商品编码查询条件
        pageNum: 1,                // 当前页码
        pageSize: 10,              // 每页条数
        total: 0                   // 总记录数
      },
      oldPurchaseType: '生产采购', // 记录旧的采购类型值
      goodsPageQuery: { // 商品分页查询参数
        pageNum: 1,
        pageSize: 10
      },
      goodsListPaginated: [] // 分页后的商品列表
    }
  },
  /**
   * 组件创建时的生命周期钩子
   * 初始化加载物料商品、产品商品、生产商品和供应商数据
   */
  created() {
    // 从路由查询字符串中获取数据
    if(this.$route.query.order != undefined){
      this.form = JSON.parse(this.$route.query.order);
    }
    
    this.fetchMaterialGoods();
    this.fetchProductGoods();
    this.fetchProduceGoods();
    this.fetchSuppliers();
    this.oldPurchaseType = this.form.purchase_type; // 初始化旧采购类型
    this.updateGoodsListPaginated(); // 初始化商品分页数据
    
    // 检查自动生成编号开关状态
    if (this.form.auto_code) {
      this.getAutoCode();
    }
    if (this.form.auto_batch_code) {
      this.getAutoBatchCode();
    }

    // 如果采购订单ID为空，则查询采购订单行信息
    if(this.form.po_id != ''){
      
      this.findOrderLine_id();
    }
  },
  methods: {

    //根据编号查询采购订单行信息
    findOrderLine_id(){
      let po_id = this.form.po_id;
      selectOrderLine_id(po_id).then(res => {
        this.goodsList = res.rows;
        this.originalGoodsList = JSON.parse(JSON.stringify(res.rows)); // 深拷贝原始数据
        this.updateGoodsListPaginated();
      })
    },
    /**
     * 根据采购类型打开对应的商品选择弹窗
     */
    handleAddGoods() {
      if (this.form.purchase_type === '物料采购') {
        this.goodsDialogMaterialVisible = true;
      } else if (this.form.purchase_type === '产品采购') {
        this.goodsDialogProductVisible = true;
      } else if (this.form.purchase_type === '生产采购') {
        this.goodsDialogProduceVisible = true;
      } else {
        this.$message.warning('请选择采购类型');
      }
    },
    
    /**
     * 处理表格多选变化事件
     * @param {Array} selection 当前选中的行数据
     */
    handleGoodsSelectChange(selection) {
      this.goodsSelected = selection;
    },
    
    /**
     * 添加选中的通用商品到订单明细
     */
    addSelectedGoods() {
      this.goodsSelected.forEach(row => {
        if (!this.goodsList.some(item => item.goods_code === row.goods_code)) {
          this.goodsList.push({
            goods_code: row.goods_code,
            goods_name: row.goods_name,
            stock_sfn: row.stock_sfn,
            unit_name: row.unit_name,
            quantity_num: 1,
            unit_price: 0,
            total_price: 0
          })
        }
      });
      this.goodsDialogVisible = false;
    },
    
    /**
     * 添加选中的物料商品到订单明细
     */
    addSelectedGoodsMaterial() {
      if (this.goodsSelected.length === 0) {
        this.$message.warning('请至少选择一个商品');
        return;
      }
      
      let hasNewItems = false;
      
      this.goodsSelected.forEach(row => {
        // 查找是否已存在相同商品
        const existingIndex = this.goodsList.findIndex(item => item.goods_code === row.material_code);
        
        if (existingIndex >= 0) {
          // 如果已存在，数量加1
          this.goodsList[existingIndex].quantity_num += 1;
          hasNewItems = true;
        } else {
          // 如果不存在，添加新商品
          this.goodsList.push({
            goods_code: row.material_code,
            goods_name: row.material_name,
            stock_sfn: row.material_sfn,
            unit_name: row.material_unit,
            quantity_num: 1,
            material_subcategory_id: row.material_subcategory_id,
            material_classification_id: row.material_classification_id,
            warehouse_id: this.form.purchase_type === '产品采购'?224:223,
            warehouse_name: this.form.purchase_type === '产品采购'?"成品仓":"物料仓",
            unit_price: row.material_purchasePrice || 0,
            total_price: row.material_purchasePrice || 0
          });
          hasNewItems = true;
        }
      });
      
      if (hasNewItems) {
        this.$message.success('商品已添加');
      }
      
      this.updateGoodsListPaginated();
      this.goodsDialogMaterialVisible = false;
    },
    
    /**
     * 添加选中的产品商品到订单明细
     */
    addSelectedGoodsProduct() {
      if (this.goodsSelected.length === 0) {
        this.$message.warning('请至少选择一个商品');
        return;
      }
      
      let hasNewItems = false;
      
      this.goodsSelected.forEach(row => {
        // 查找是否已存在相同商品
        const existingIndex = this.goodsList.findIndex(item => item.goods_code === row.product_code);
        
        if (existingIndex >= 0) {
          // 如果已存在，数量加1
          this.goodsList[existingIndex].quantity_num += 1;
          hasNewItems = true;
        } else {
          // 如果不存在，添加新商品
          this.goodsList.push({
            goods_code: row.product_code,
            goods_name: row.product_name,
            stock_sfn: row.product_sfn,
            unit_name: row.product_unit,
            quantity_num: 1,
            material_subcategory_id: row.material_subcategory_id,
            material_classification_id: row.material_classification_id,
            warehouse_id: this.form.purchase_type === '产品采购'?224:223,
            warehouse_name: this.form.purchase_type === '产品采购'?"成品仓":"物料仓",
            unit_price: row.purchaseprice || 0,
            total_price: row.purchaseprice || 0
          });
          hasNewItems = true;
        }
      });
      
      if (hasNewItems) {
        this.$message.success('商品已添加');
      }
      
      this.updateGoodsListPaginated();
      this.goodsDialogProductVisible = false;
    },
    
    /**
     * 添加选中的生产商品到订单明细
     */
    addSelectedGoodsProduce() {
      if (this.goodsSelected.length === 0) {
        this.$message.warning('请至少选择一个商品');
        return;
      }
      
      let hasNewItems = false;
      
      this.goodsSelected.forEach(row => {
        // 查找是否已存在相同商品
        const existingIndex = this.goodsList.findIndex(item => item.goods_code === row.product_code);
        
        if (existingIndex >= 0) {
          // 如果已存在，数量加1
          this.goodsList[existingIndex].quantity_num += 1;
          hasNewItems = true;
        } else {
          // 如果不存在，添加新商品
          this.goodsList.push({
            goods_code: row.product_code,
            goods_name: row.product_name,
            stock_sfn: row.material_sfn,
            unit_name: row.material_unit,
            quantity_num: row.required_quantity,
            material_subcategory_id: row.material_subcategory_id,
            material_classification_id: row.material_classification_id,
            warehouse_id: this.form.purchase_type === '产品采购'?224:223,
            warehouse_name: this.form.purchase_type === '产品采购'?"成品仓":"物料仓",
            unit_price: row.material_purchasePrice || 0,
            total_price: row.material_purchasePrice || 0
          });
          hasNewItems = true;
        }
      });
      
      if (hasNewItems) {
        this.$message.success('商品已添加');
      }
      
      this.updateGoodsListPaginated();
      this.goodsDialogProduceVisible = false;
    },
    
    /**
     * 从订单明细中移除指定索引的商品
     * @param {Number} index 要移除的商品索引
     */
    removeGoods(index) {
      this.goodsList.splice(index, 1);
      this.updateGoodsListPaginated();
    },
    
    /**
     * 计算商品行的总价
     * @param {Object} row 商品行数据
     * @return {String} 格式化后的总价
     */
    calcTotalPrice(row) {
      const qty = Number(row.quantity_num) || 0
      const price = Number(row.unit_price) || 0
      // 截断多余的数字
      const truncatedTotal = Math.trunc(qty * price * 100) / 100;
      row.total_price = truncatedTotal.toFixed(2);
      return truncatedTotal.toFixed(2);
    },
    
    /**
     * 处理采购类型变化事件
     * @param {String} newType 新选择的采购类型
     */
    handlePurchaseTypeChange(newType) {
      // 保存旧的采购类型值
      const oldType = this.oldPurchaseType || '物料采购';
      
      // 清空已选择的商品列表
      if (this.goodsList.length > 0) {
        this.$confirm('更改采购类型将清空已选择的商品，是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.goodsList = [];
          this.updateGoodsListPaginated();
          this.$message.success('已清空商品列表');
          // 更新旧类型记录
          this.oldPurchaseType = newType;
        }).catch(() => {
          // 用户取消，恢复原来的采购类型
          this.form.purchase_type = oldType;
          this.$message.info('已取消更改采购类型');
        });
      } else {
        // 没有商品时直接更新旧类型记录
        this.oldPurchaseType = newType;
      }
    },
    
    /**
     * 点击供应商表格行，直接选中并关闭弹窗
     * @param {Object} row 当前点击的行数据
     */
    selectSupplierAndClose(row) {
      if (row) {
        this.form.supplier_id = row.supplier_id;
        this.form.supplier_name = row.supplier_name;
        this.supplierDialogVisible = false;
      }
    },
    
    /**
     * 处理供应商搜索按钮点击事件
     */
    handleSupplierSearch() {
      this.supplierQuery.pageNum = 1;
      this.fetchSuppliers();
    },
    
    /**
     * 重置供应商搜索条件并刷新数据
     */
    handleSupplierReset() {
      this.supplierQuery.name = '';
      this.supplierQuery.pageNum = 1;
      this.supplierQuery.pageSize = 10;
      this.fetchSuppliers();
    },
    
    /**
     * 获取物料商品数据
     */
    fetchMaterialGoods() {
      //this.$message.info("当前页码:"+this.goodsMaterialQuery.pageNum)
      listMaterialGoods(this.goodsMaterialQuery).then(resp => {
        if (resp.code === 200) {
          this.goodsMaterialList = resp.rows || [];
          this.goodsMaterialQuery.total = resp.total || 0;
        }
      }).catch(() => {
        this.$message.error('获取物料商品请求异常');
      });
    },
    
    /**
     * 获取产品商品数据
     */
    fetchProductGoods() {
      //this.$message.info("当前页码:"+this.goodsProductQuery.product_code)
      listProductGoods(this.goodsProductQuery).then(resp => {
        if (resp.code === 200) {
          this.goodsProductList = resp.rows || [];
          this.goodsProductQuery.total = resp.total || 0;
        }
      }).catch(() => {
        this.$message.error('获取产品商品请求异常');
      });
    },
    
    /**
     * 物料商品搜索按钮点击事件
     */
    handleMaterialSearch() {
      this.goodsMaterialQuery.pageNum = 1;
      this.fetchMaterialGoods();
    },
    
    /**
     * 重置物料商品搜索条件并刷新数据
     */
    handleMaterialReset() {
      this.goodsMaterialQuery.material_code = '';
      this.goodsMaterialQuery.pageNum = 1;
      this.fetchMaterialGoods();
    },
    
    /**
     * 产品商品搜索按钮点击事件
     */
    handleProductSearch() {
      this.goodsProductQuery.pageNum = 1;
      this.fetchProductGoods();
    },
    
    /**
     * 重置产品商品搜索条件并刷新数据
     */
    handleProductReset() {
      this.goodsProductQuery.product_code = '';
      this.goodsProductQuery.pageNum = 1;
      this.fetchProductGoods();
    },
    
    /**
     * 生产商品搜索按钮点击事件
     */
    handleProduceSearch() {
      this.goodsProduceQuery.pageNum = 1;
      this.fetchProduceGoods();
    },
    
    /**
     * 重置生产商品搜索条件并刷新数据
     */
    handleProduceReset() {
      this.goodsProduceQuery.product_code = '';
      this.goodsProduceQuery.pageNum = 1;
      this.fetchProduceGoods();
    },
    
    /**
     * 获取生产商品数据
     */
    fetchProduceGoods() {
      //this.$message.info("当前页码:"+this.goodsProduceQuery.pageNum)
      listPurchaseGoods(this.goodsProduceQuery).then(resp => {
        if (resp.code === 200) {
          this.goodsProduceList = resp.rows || [];
          this.goodsProduceQuery.total = resp.total || 0;
        } else {
          this.$message.error(resp.msg || '获取生产商品失败');
        }
      }).catch(() => {
        this.$message.error('获取生产商品请求异常');
      });
    },
    
    /**
     * 获取供应商数据
     */
    fetchSuppliers() {
      listSupplier(this.supplierQuery).then(resp => {
        if (resp.code === 200) {
          this.supplierSelectList = resp.rows || [];
          this.supplierQuery.total = resp.total || 0;
        } else {
          this.$message.error(resp.msg || '获取供应商数据失败');
        }
      }).catch(() => {
        this.$message.error('获取供应商数据请求异常');
      });
    },
    
    /**
     * 保存并提交
     */
    handleSubmitAndSubmit() {
      this.form.status = '2'; // 设置状态为采购中
      this.handleSubmit();
    },

    /**
     * 处理表单提交事件
     */
    async handleSubmit() {
      this.$refs.formRef.validate(async valid => {
        if (!valid) return
        if (!this.goodsList.length) {
          this.$message.warning('请添加至少一件商品')
          return
        }
        
        const loading = this.$loading({
          lock: true,
          text: '正在提交数据，请稍候...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });

        // 如果是自动生成编号，并且是新增状态，则消费编号
        if (this.form.auto_code && !this.form.po_id) {
          try {
            const res = await getAutoNumbersConsume(26);
            if (res.code === 200) {
              this.form.po_code = res.msg;
            } else {
              this.$message.error(res.msg || '获取最终编号失败');
              loading.close();
              return;
            }
          } catch (err) {
            this.$message.error('获取最终编号请求异常');
            loading.close();
            return;
          }
        }

        if (this.form.auto_batch_code && !this.form.po_id) {
          try {
            const res = await getAutoNumbersConsume(28);
            if (res.code === 200) {
              this.form.batch_code = res.msg;
            } else {
              this.$message.error(res.msg || '获取最终批次编号失败');
              loading.close();
              return;
            }
          } catch (err) {
            this.$message.error('获取最终批次编号请求异常');
            loading.close();
            return;
          }
        }
        
        this.form.create_by = this.$store.getters.name //当地登录的用户名
        this.form.update_by = this.form.create_by

        // 格式化日期为后端需要的格式 yyyy-MM-dd HH:mm:ss
        const formData = JSON.parse(JSON.stringify(this.form)); // 深拷贝表单数据
        if (formData.expected_delivery_date) {
          const date = new Date(formData.expected_delivery_date);
          formData.expected_delivery_date = this.formatDateTime(date);
        }

        // 调用后端接口保存数据
        addPurchaseOrder(formData, this.goodsList).then(res => {
          loading.close(); // 关闭加载状态
          if (res.code === 200) {
            if(this.form.po_id == ''){
              this.$message.success('采购订单创建成功');
              this.$router.push('/ck/PurchaseOrder');
            }else{
              this.$message.success('采购订单修改成功');
              this.$router.push('/ck/PurchaseOrder');
            }
          } else {
            this.$message.error(res.msg || '采购订单创建失败');
          }
        }).catch(err => {
          loading.close(); // 关闭加载状态
          this.$message.error('系统错误，请稍后重试');
          console.error('提交采购订单失败:', err);
        });
      })
    },
    
    /**
     * 格式化日期时间为 yyyy-MM-dd HH:mm:ss 格式
     * @param {Date} date 日期对象
     * @return {String} 格式化后的日期字符串
     */
    formatDateTime(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    
    /**
     * 处理取消按钮点击事件，返回上一页
     */
    handleCancel() {
      this.$router.back()
    },

    /**
     * 重置采购商品列表
     */
    handleResetGoodsList() {
      const isEditMode = !!this.form.po_id;

      if (this.goodsList.length === 0 && !isEditMode) {
        this.$message.info('列表已为空');
        return;
      }
      
      const confirmText = isEditMode 
        ? '是否确认将商品列表还原到初始状态？' 
        : '是否确认重置采购商品列表？';
      
      const successText = isEditMode ? '商品列表已还原' : '商品列表已重置';

      this.$confirm(confirmText, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (isEditMode) {
          // 修改模式：还原
          this.goodsList = JSON.parse(JSON.stringify(this.originalGoodsList));
        } else {
          // 新增模式：清空
          this.goodsList = [];
        }
        this.updateGoodsListPaginated();
        this.$message.success(successText);
      }).catch(() => {});
    },

    /**
     * 处理商品分页变化
     */
    handleGoodsPageChange() {
      this.updateGoodsListPaginated();
    },

    /**
     * 更新分页后的商品列表
     */
    updateGoodsListPaginated() {
      this.goodsListPaginated = this.goodsList.slice(
        (this.goodsPageQuery.pageNum - 1) * this.goodsPageQuery.pageSize,
        this.goodsPageQuery.pageNum * this.goodsPageQuery.pageSize
      );
    },

    /**
     * 处理自动生成编号开关变化
     * @param {Boolean} val 开关状态
     */
    handleAutoCodeChange(val) {
      if (val) {
        // 开启自动生成，调用接口获取编号
        this.getAutoCode();
      } else {
        // 关闭自动生成，清空编号
        this.form.po_code = '';
      }
    },
    
    handleAutoBatchCodeChange(val) {
      if (val) {
        this.getAutoBatchCode();
      } else {
        this.form.batch_code = '';
      }
    },
    
    /**
     * 获取自动生成的编号
     */
    getAutoCode() {
      getAutoNumbers(26).then(res => {
        if (res.code === 200) {
          this.form.po_code = res.msg;
        } else {
          this.$message.error(res.msg || '获取编号失败');
          this.form.auto_code = false;
        }
      }).catch(err => {
        this.$message.error('获取编号请求异常');
        this.form.auto_code = false;
      });
    },

    getAutoBatchCode() {
      getAutoNumbers(28).then(res => {
        if (res.code === 200) {
          this.form.batch_code = res.msg;
        } else {
          this.$message.error(res.msg || '获取批次编号失败');
          this.form.auto_batch_code = false;
        }
      }).catch(err => {
        this.$message.error('获取批次编号请求异常');
        this.form.auto_batch_code = false;
      });
    }
  }
}
</script>

<style scoped>
/**
 * 容器样式
 */
.app-container {
  padding: 20px;
  width: 100%;
  box-sizing: border-box;
}

/**
 * 基础信息卡片样式
 */
.base-info-card {
  margin-bottom: 20px;
  border-radius: 4px;
  background: #fff;
}

/**
 * 基础信息标题样式
 */
.base-info-title {
  font-weight: bold;
  font-size: 16px;
  padding: 4px 0;
}

/**
 * 必填项标记样式
 */
.required {
  color: #f56c6c;
  margin-right: 2px;
}

/**
 * 商品列表区域样式
 */
.goods-section {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.03);
}

/**
 * 表单样式调整
 */
.base-info-form {
  padding: 0 10px 0 0;
}

/**
 * 表单项间距调整
 */
.base-info-form .el-form-item {
  margin-bottom: 16px;
}

/**
 * 输入框附加按钮样式调整
 */
.base-info-form .el-input-group__append,
.base-info-form .el-input-group__prepend {
  padding: 0 8px;
}

/**
 * 只读输入框样式
 */
.base-info-form .el-input[readonly] {
  background: #f5f7fa;
}

/**
 * 响应式布局适配
 */
@media (max-width: 1200px) {
  .base-info-form .el-col-8 {
    width: 100%;
    max-width: 100%;
    flex: 0 0 100%;
  }
}

/**
 * 输入框与开关组合的样式
 */
.input-switch-group {
  display: flex;
  align-items: center;
}

/**
 * 输入框样式
 */
.input-switch-group .el-input {
  flex: 1;
}

/**
 * 开关标签文字样式
 */
.switch-label {
  margin-left: 6px;
  color: #909399;
  font-size: 14px;
  white-space: nowrap;
}
</style>
